package edu.kpi.pzks2.simulator.impl;

import java.util.List;

import edu.kpi.pzks2.graph.Edge;
import edu.kpi.pzks2.graph.Node;
import edu.kpi.pzks2.simulator.core.Simulator;
import edu.kpi.pzks2.simulator.core.router.Router;
import edu.kpi.pzks2.simulator.core.router.RouterFactory;
import edu.kpi.pzks2.simulator.processing.Processor;
import edu.uci.ics.jung.algorithms.shortestpath.DijkstraShortestPath;
import edu.uci.ics.jung.graph.Graph;
import edu.uci.ics.jung.graph.util.Pair;

public class SimpleRouterImpl implements Router {
    private final Graph<Node, Edge> processorGraph;
    private final Simulator simulator;
    
    private SimpleRouterImpl(final Graph<Node, Edge> processorGraph, final Simulator simulator) {
        this.processorGraph = processorGraph;
        this.simulator = simulator;
    }
    
    public Processor route(Processor from, Processor to) {
        final DijkstraShortestPath<Node, Edge> shortPath = new DijkstraShortestPath<Node, Edge>(processorGraph);
        final List<Edge> path = shortPath.getPath(from.getNode(), to.getNode());
        
        final Pair<Node> ends = processorGraph.getEndpoints(path.get(0));
        Node toNode;
        if (ends.getFirst() == from.getNode()) {
            toNode = ends.getSecond();
        } else {
            toNode = ends.getFirst();
        }
        
        return simulator.getCorrespondProcessor(toNode);
    }
    
    public static class SimpleRouterFactory implements RouterFactory {
        public Router createRouter(final Graph<Node, Edge> processorGraph, final Simulator simulator) {
            return new SimpleRouterImpl(processorGraph, simulator);
        }
    }
}
